import {Form, Input, message, Modal, Select} from "antd";
import {forwardRef, useImperativeHandle, useState} from "react";
import {addProjectApi, projectTypeApi} from "../../Api/researchProject.ts";

const AddDialog = (props:any,ref) => {
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [projectName, setProjectName] = useState('');
    const [projectType, setProjectType] = useState('');
    const [projectTypeOptions, setProjectTypeOptions] = useState([]);
    const [form] = Form.useForm(); // 获取 form 实例
    //用useImperativeHandle暴露一些外部ref能访问的属性
    useImperativeHandle(ref, () => {
        return {
            open: ()=>{
                form.resetFields(); // 重置表单
                getProjectType()
                setIsModalOpen(true);
            },
        };
    });
    async function getProjectType(){
        const {code,data} = await projectTypeApi()
        if(code===0){
            setProjectTypeOptions(data.map((i:any)=>{
                return {
                    label:i.msg,
                    value:i.code
                }
            }))
        }
    }
    const handleOk = () => {
        form.validateFields().then(async ()=>{
            const params={
                name: projectName,
                projectType: projectType,
            }
            const {code,msg} = await addProjectApi(params)
            if(code===0){
                message.success('新增项目成功')
                setIsModalOpen(false);
            }else{
                message.warning(msg)
            }
        })
    };

    const handleCancel = () => {
        setIsModalOpen(false);
    };
    return (
        <>
            <Modal title="新增项目" open={isModalOpen} onOk={handleOk} onCancel={handleCancel} okText={'确认'} cancelText={'取消'} >
                <Form
                    form={form} // 绑定 form 实例
                    name="addProjectForm"
                >
                    <Form.Item
                        label="项目名称"
                        name="projectName"
                        rules={[{ required: true, message: '请输入项目名称!' }]}
                    >
                        <Input value={projectName} onChange={(e) => setProjectName(e.target.value)} />
                    </Form.Item>
                    <Form.Item
                        label="项目类型"
                        name="projectType"
                        rules={[{ required: true, message: '请输入项目类型!' }]}
                    >
                        <Select
                            onChange={(e)=>{
                                setProjectType(e)
                            }}
                            options={projectTypeOptions}
                        />
                    </Form.Item>
                </Form>
            </Modal>
        </>
    )
}

export default forwardRef(AddDialog)